import axios from 'axios'
import { message as Message } from 'ant-design-vue'
import errorCode from '@/utils/errorCode'
import { BASE_URL } from './config'

// 创建axios实例
const request = axios.create({
  baseURL: BASE_URL,
  timeout: 10000
})

// 错误信息处理
const handleError = (message) => {
  if (message === 'Network Error') {
    return 'Backend interface connection abnormality'
  } else if (message.includes('timeout')) {
    return 'System interface request timeout'
  } else if (message.includes('Request failed, status code error')) {
    return 'System Interface ' + message.substr(message.length - 3) + ' abnormal'
  }
  return message
}

// 错误处理函数
const errorHandler = (error) => {
  console.error('Request error:', error)
  const errorMessage = handleError(error.message)
  if (errorMessage) {
    Message.error(errorMessage)
  }
  return Promise.reject(error)
}

// 请求拦截器
const requestInterceptor = (config) => {
  const authorization = sessionStorage.getItem('authorization')
  if (authorization) {
    config.headers.Authorization = `Basic ${authorization}`
  }
  return config
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { code, errorCode: responseErrorCode, msg } = response.data
  const errorMessage = errorCode[responseErrorCode] || msg || errorCode['default']

  // 如果响应类型为blob或arraybuffer，直接返回数据
  if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
    return response.data
  }

  // 错误码处理
  if (code === 500 || code !== 0) {
    Message.error(errorMessage)
    return Promise.reject(errorMessage)
  }

  return response.data
}

// 注册请求和响应拦截器
request.interceptors.request.use(requestInterceptor, errorHandler)
request.interceptors.response.use(responseInterceptor, errorHandler)

export default request
